package com.sheng.leetcode.year2022.swordfingeroffer.day06;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author liusheng
 * @date 2022/09/05
 *
 * 剑指 Offer 32 - I. 从上到下打印二叉树
 *
 * 从上到下打印出二叉树的每个节点，同一层的节点按照从左到右的顺序打印。
 *
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回：
 *
 * [3,9,20,15,7]
 *
 * 提示：
 *
 * 节点总数 <= 1000
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Sword0032 {

    @Test
    public void test01() {
        TreeNode root = new TreeNode(3);
        TreeNode right = new TreeNode(20);
        right.left = new TreeNode(15);
        right.right = new TreeNode(7);
        root.left = new TreeNode(9);
        root.right = right;
        System.out.println(Arrays.toString(new Solution().levelOrder(root)));
    }
}

// Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {

    List<TreeNode> list;
    public int[] levelOrder(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        list = new ArrayList<>();
        list.add(root);
        // 层序遍历
        bfs(list);
        return list.stream().mapToInt(o -> o.val).toArray();
    }

    public void bfs(List<TreeNode> treeNodes) {
        List<TreeNode> nodes = new ArrayList<>();
        for (TreeNode node : treeNodes) {
            if (node.left != null) {
                nodes.add(node.left);
            }
            if (node.right != null) {
                nodes.add(node.right);
            }
        }
        if (nodes.size() > 0) {
            list.addAll(nodes);
            bfs(nodes);
        }
    }
}
